﻿using B.S.Data.MES.API.Applications.QualityManagement.ExamineProjectCommand.Commands;
using B.S.Data.MES.API.Dto.ExamineProjectDTO;
using B.S.Domain.BasicData.QualityManagement;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;

namespace B.S.Data.MES.API.Applications.QualityManagement.ExamineProjectCommand.CommandHandlers
{
    public class GetExamineProjectCommandHandler : IRequestHandler<GetExamineProjectCommand, APIRequst<APIPageing<List<ProjectDTO>>>>
    {
        private readonly IBaseRepository<ExamineProject> _examineprojectRepository;
        private readonly IBaseRepository<ExamineType> _examinetypeRepository;
        public GetExamineProjectCommandHandler(IBaseRepository<ExamineProject> examineprojectRepository, IBaseRepository<ExamineType> examinetypeRepository)
        {
            _examineprojectRepository = examineprojectRepository;
            _examinetypeRepository = examinetypeRepository;

        }
        public Task<APIRequst<APIPageing<List<ProjectDTO>>>> Handle(GetExamineProjectCommand request, CancellationToken cancellationToken)
        {
            APIRequst<APIPageing<List<ProjectDTO>>> result = new APIRequst<APIPageing<List<ProjectDTO>>>();

            var list = from a in _examineprojectRepository.GetAll()
                       join b in _examinetypeRepository.GetAll() on a.ExamineId equals b.ExamineId
                       where !a.isDel
                       select new ProjectDTO
                       {
                           ExamineProjectId = a.ExamineProjectId,
                           ExamineProjectName= a.ExamineProjectName,
                           ExamineId=b.ExamineId,
                           ExamineName=b.ExamineName,
                           ProjectMethod=a.ProjectMethod,
                           ProjectStandard=a.ProjectStandard,
                           Unit=a.Unit,
                           UpperLimit=a.UpperLimit,
                           LowerLimit=a.LowerLimit,
                           ProjectRemark=a.ProjectRemark,
                       };
            
            if(!string.IsNullOrEmpty(request.ExamineProjectName))
            {
                list = list.Where(x => x.ExamineProjectName.Contains(request.ExamineProjectName));

            }
            var recordcount = list.Count();
            var pagecount = (int)Math.Ceiling(recordcount * 1.0 / request.PageSize);

            list = list.OrderByDescending(x => x.ExamineProjectId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            APIPageing<List<ProjectDTO>> paing = new APIPageing<List<ProjectDTO>>();
            paing.TotalCount = recordcount;
            paing.Total=pagecount;
            paing.Data = list.ToList();
           
            result.Data = paing;
            return Task.FromResult(result);

        }
    }
}
